﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using MinistryStandardPlatformWeb.Models.ReportCenter;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("44")]
    public class OfflineAnalysisController : Controller
    {
        //
        // GET: /OfflineAnalysis/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetData(List<string> vehicleNums)
        {
            if (vehicleNums != null && vehicleNums.Count != 0)
            {
                string sql = "select t1.vehiclenum mNum,"
                + "cast(cast(t1.longitudeoffset as decimal(20,8)) as varchar(20)) mLng,"
                + "cast(cast(t1.latitudeoffset as decimal(20,8)) as varchar(20)) mLat,"
                + "t1.recordtime as mLastTime "
                + "from gpsbasic t1 "
                + "where ";
                for (int i = 0; i < vehicleNums.Count; i++)
                {
                    if (i == 0)
                    {
                        sql += "(";
                    }
                    sql += "t1.vehiclenum='" + vehicleNums[i] + "' or ";
                    if (i == vehicleNums.Count - 1)
                    {
                        sql += "1=0) ";
                    }
                }
                sql += "and t1.id=(select top 1 t2.id from gpsbasic t2 where t2.vehiclenum=t1.vehiclenum order by t2.recordtime desc)";
                string historyStr = RealTimeGet.getReportFromGeoBase(
                    CommonFunctions.GetLoginUser().UserId,
                    sql,
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    "0");
                List<OfflineAnalysis> modelList = new List<OfflineAnalysis>();
                if (historyStr != "error" && historyStr != "")
                {
                    try
                    {
                        modelList = CommonFunctions.JsonStrToObject<List<OfflineAnalysis>>(historyStr);
                        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            OfflineAnalysis model = modelList[i];
                            if (i < 20)
                            {
                                model.mAddr = geoHelper.GgpsTranslate2BaiduPoi(model.mLng, model.mLat);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
                else
                {
                }
                /*如果历史表没有该车的最近上传gps信息，构造一个*/
                if (modelList.Count != vehicleNums.Count)
                {
                    foreach (string vehiclenum in vehicleNums)
                    {
                        bool bIn = false; ;
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            if (modelList[i].mNum.Equals(vehiclenum))
                            {
                                bIn = true;
                                break;
                            }
                        }
                        if(!bIn)
                        {
                            OfflineAnalysis tmp = new OfflineAnalysis();
                            tmp.mNum = vehiclenum;
                            modelList.Add(tmp);
                        }
                    }
                }
                var json = new
                {
                    total = modelList.Count,
                    rows = modelList
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        /*解析地理位置*/
        [HttpPost]
        public ActionResult ParseAddr(string key, int page, List<string> lngs, List<string> lats)
        {//key为查询批次的唯一标示，防止前台点击“查询”重新查询另一批数据时，后台处理返回数据与前台数据不唯一
            if (lngs.Count == lats.Count)
            {
                MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                List<string> pois = new List<string>();
                for (int i = 0; i < lngs.Count; i++)
                {
                    if (lngs[i] == "" || lats[i] == "" || lngs[i] == "null" || lats[i] == "null")
                    {
                        pois.Add("");
                    }
                    else
                    {
                        pois.Add(geoHelper.GgpsTranslate2BaiduPoi(lngs[i], lats[i]));
                    }
                }
                var json = new
                {
                    key = key,
                    page = page,
                    pois = (from r in pois
                            select r).ToArray()
                };
                return Json(json);
            }
            return null;
        }

        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportExcel()
        {
            List<OfflineAnalysis> list = CommonFunctions.JsonStrToObject<List<OfflineAnalysis>>(Request.Form["data"]);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号","车牌号", "SIM卡号","单位名称","最后上报时间", "离线时长", "离线位置" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mName);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", list[i].mSim);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mDepart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mLastTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mInterval);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mAddr);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", "离线分析.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }
    }
}
